package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service
public class VideoApiImpl implements VideoApi{
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void post(Video video) {
        long timeMillis = System.currentTimeMillis();
        video.setCreated(timeMillis);
        mongoTemplate.insert(video);
    }

    @Override
    public PageResult findPage(Long page, Long pagesize) {
        Query query = new Query();
        List<Video> videos = new ArrayList<>();
        long total = mongoTemplate.count(query, Video.class);
        if (total>0){
            query.skip((page-1)*pagesize).limit(pagesize.intValue());
            query.with(Sort.by(Sort.Order.desc("created")));
             videos = mongoTemplate.find(query, Video.class);
        }
        return PageResult.pageResult(page,pagesize,videos,total);
    }

    @Override
    public void userFocus(FollowUser followUser) {
        followUser.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(followUser);
    }

    @Override
    public void userUnFocus(FollowUser followUser) {
        Query query = new Query(Criteria.where("userId").is(followUser.getUserId()).and("followUserId").is(followUser.getFollowUserId()));
        mongoTemplate.remove(query,FollowUser.class);
    }
}
